package com.csun.cmny.provider.netty;

import com.csun.cmny.provider.netty.server.Constant;
import com.csun.cmny.provider.netty.server.NettyServer;
import com.google.common.collect.Lists;
import io.netty.bootstrap.AbstractBootstrap;
import io.netty.channel.ChannelFuture;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-04-02 19:04
 * @Description:
 */
@Slf4j
@Component
public class NettyInitRunner implements CommandLineRunner {

    @Resource
    private TaskExecutor taskExecutor;

    public static ConcurrentMap<Integer, NettyServer> nettyServerMap = new ConcurrentHashMap<Integer, NettyServer>();

    public List<ChannelFuture> channelFutureList = Lists.newArrayList();

    @Override
    public void run(String... args) throws Exception {

        taskExecutor.execute(() -> {
            try {
                for (NettyServer nettyServer : nettyServerMap.values()) {

                    if (nettyServer.getType() == Constant.SOCK_STREAM) {
                        ChannelFuture channelFuture = nettyServer.getServerBootstrap().bind(nettyServer.getPort()).sync();
                        channelFutureList.add(channelFuture);
                    } else if (nettyServer.getType() == Constant.SOCK_DGRAM) {
                        ChannelFuture channelFuture = nettyServer.getBootstrap().bind(nettyServer.getPort()).sync();
                        channelFutureList.add(channelFuture);
                    }

                    log.info("netty server port {} is bind......", nettyServer.getPort());
                }
            } catch (Exception e) {
                log.error("netty init run error...");
            }
        });

        for (ChannelFuture channelFuture : channelFutureList) {
            channelFuture.channel().closeFuture().sync();
        }

        log.info("###NettyInitRunner finish<<<<<<<<<<<<<");
    }
}
